<?
class AZLib
{
    static $check_uri = false;

    static function get_config($update_cache = 0, $delcache = false) {
        if (!CGlobal::$configs || $delcache || $update_cache) {
            if (AZArrCache::is_not_cached('config_arr', 0, '', $delcache)) {
                if (!$delcache) {
                    $re = DB::query('SELECT * FROM configs');

                    if ($re) {
                        while ($value = mysql_fetch_assoc($re)) {
                            CGlobal::$configs[$value['conf_key']] = $value;
                        }
                    }

                    AZArrCache::set(CGlobal::$configs);
                }
            } else {
                CGlobal::$configs = AZArrCache::$arr_cache;
                AZArrCache::$arr_cache = array();
            }
        }
    }

    static function getCats($update_cache = 0, $delcache = false) 
    {
        if (!CGlobal::$allCategories || $delcache || $update_cache) 
        {
            if (AZArrCache::is_not_cached('cat_arr', 0, '', $delcache)) 
            {
                if (!$delcache) {
                    $re = DB::query("SELECT zoneid, catid,category_zone_cat.position FROM category_zone_cat LEFT JOIN category_zone ON category_zone_cat.zoneid = category_zone.id ORDER BY category_zone.position,category_zone_cat.position");

                    $cat_zones = array();
                    $allZoneCats = array();
                    if ($re) {
                        while ($zcat = mysql_fetch_assoc($re)) {
                            $allZoneCats[$zcat['zoneid']][$zcat['catid']] = $zcat['catid'];

                            $cat_zones[$zcat['catid']][$zcat['zoneid']] = $zcat['zoneid'];
                        }
                    }

                    $re = DB::query('SELECT id, name, brief_name, total_item, position, class  FROM category_zone WHERE status=1 ORDER BY position', __LINE__ . __FILE__);
                    if ($re) {
                        while ($zone = mysql_fetch_assoc($re)) {
                            $zone['ebname'] = AZLib::safe_title($zone['name']);

                            if (isset($allZoneCats[$zone['id']])) {
                                $zone['cats'] = $allZoneCats[$zone['id']];
                            } else {
                                $zone['cats'] = array();
                            }

                            CGlobal::$allZones[$zone['id']] = $zone;
                        }
                    }

                    $re = DB::query('SELECT id,ref_id, name, brief_name, status, parent_id, keywords, description, position, tag_search, img_server, price_str, recomend FROM category WHERE status!="HIDE" ORDER BY parent_id, position', __LINE__ . __FILE__);

                    if ($re) {
                        while ($cat = mysql_fetch_assoc($re)) {
                            $cat['ebname'] = AZLib::safe_title($cat['name']);
                            $cat['nice_name'] = $cat['ebname'];

                            if ($cat['parent_id']) {//Nếu là danh mục cấp 2
                                if (isset(CGlobal::$allCategories[$cat['parent_id']])) {//Nếu tồn tại danh mục cha
                                    if ($cat['parent_id'] == 104) {//Hàng hiệu
                                        $cat['nice_name'] = CGlobal::$allCategories[$cat['parent_id']]['nice_name'] . "-{$cat['ebname']}";
                                    } else {
                                        $cat['nice_name'] = CGlobal::$allCategories[$cat['parent_id']]['nice_name'];
                                    }

                                    if (CGlobal::$allCategories[$cat['parent_id']]['parent_id']) {//Nếu là danh mục cấp 3
                                        $level2_id = $cat['parent_id'];
                                        $top_id = CGlobal::$allCategories[$cat['parent_id']]['parent_id'];

                                        if (isset(CGlobal::$allCategories[$top_id])) {//Nếu tồn tại danh mục cha
                                            $cat['nice_name'] = CGlobal::$allCategories[$top_id]['nice_name'];
                                        }
                                    } else {
                                        CGlobal::$subCategories[$cat['parent_id']][$cat['id']] = $cat;
                                    }
                                } else {
                                    CGlobal::$subCategories[$cat['parent_id']][$cat['id']] = $cat;
                                }
                            } elseif (!isset(CGlobal::$subCategories[$cat['id']])) {
                                CGlobal::$subCategories[$cat['id']] = array();

                                if (isset($cat_zones[$cat['id']])) {
                                    $cat['zones'] = $cat_zones[$cat['id']];
                                } else {
                                    $cat['zones'] = array();
                                }
                            }

                            CGlobal::$allCategories[$cat['id']] = $cat;
                        }
                    }

                    AZArrCache::set(array(
                                'allZones' => CGlobal::$allZones,
                                'allCategories' => CGlobal::$allCategories,
                                'subCategories' => CGlobal::$subCategories,
                            ));
                } else {
                    /* foreach (CGlobal::$my_server as $server){//Tạo lại file js cho chuyên mục
                      @fopen("http://$server/catgen.php","r");
                      } */

                   // @fopen(WEB_ROOT . "seo.php", "r");

                    /*$js_ver = rand(1, 1000);
                    AZMemcache::do_put("cat_ver:", $js_ver);*/
                }
            } else {
                CGlobal::$allZones = AZArrCache::$arr_cache['allZones'];
                CGlobal::$allCategories = AZArrCache::$arr_cache['allCategories'];
                CGlobal::$subCategories = AZArrCache::$arr_cache['subCategories'];

                AZArrCache::$arr_cache = array();
            }
        }
    }
   
    static function getFilters($delcache = false)
    {
    	self::getCats();
    	
		if(AZArrCache::is_not_cached('filters_arr',0,'',$delcache))
		{
			if(!$delcache)
			{
				$re = DB::query('SELECT * FROM filter ORDER BY fgid, pos');
				
				if($re)
				{
					while ($filter = mysql_fetch_assoc($re))
					{
						if(!isset(CGlobal::$all_filters[$filter['fgid']]))
						{
							CGlobal::$all_filters[$filter['fgid']] = array();
						}
						
						CGlobal::$all_filters[$filter['fgid']][$filter['id']]  = $filter;
						
						CGlobal::$allFilters[$filter['id']]  = $filter;
					}									
				}
				
				$re = DB::query('SELECT * FROM filter_group ORDER BY pos');
				
				if($re)
				{
					while ($group_filter = mysql_fetch_assoc($re))
					{
						CGlobal::$all_gfilters[$group_filter['id']] = $group_filter;
						
						if($group_filter['catids'] != '')
						{
							$catids = explode(',',$group_filter['catids']);
							
							if(isset(CGlobal::$all_filters[$group_filter['id']]))
							{
								$group_filter['filters'] = CGlobal::$all_filters[$group_filter['id']];
							}
								
							if($catids)
							{
								foreach ($catids as $catid)	
								{
									if($catid != '' && isset(CGlobal::$allCategories[$catid]))	
									{
										if(!isset(CGlobal::$filters[$catid]))
										{
											CGlobal::$filters[$catid] = array();
										}
										
										CGlobal::$filters[$catid][$group_filter['id']] = $group_filter;
									}
								}
							}
						}
					}									
				}
				
				AZArrCache::set(array(
									'allFilters'	=>CGlobal::$allFilters,
									'filters'		=>CGlobal::$filters,
									'all_filters'	=>CGlobal::$all_filters,
									'all_gfilters'	=>CGlobal::$all_gfilters
									));
			}
		}
		else{
			CGlobal::$allFilters 	= AZArrCache::$arr_cache['allFilters'];
			CGlobal::$filters 		= AZArrCache::$arr_cache['filters'];
			CGlobal::$all_filters 	= AZArrCache::$arr_cache['all_filters'];
			CGlobal::$all_gfilters 	= AZArrCache::$arr_cache['all_gfilters'];
			
			AZArrCache::$arr_cache 	= array();
		}
	}
	
	static function getNewsCats($delcache = false){
		if(AZArrCache::is_not_cached('news_cat_arr',0,'',$delcache)){
			if(!$delcache){
				global $oDB;
				
				$re=DB::query('SELECT * FROM news_categories ORDER BY position',__LINE__.__FILE__);
				$allNewsCategories=array();
				
				if($re){
					while ($cat = mysql_fetch_assoc($re))
					{
						$cat['azname'] = AZLib::safe_title($cat['name']);
						
						CGlobal::$allNewsCategories[$cat['id']] = $cat;
					}									
				}
				
				AZArrCache::set(array(
										'allNewsCategories'	=> CGlobal::$allNewsCategories,
										));
			}
			else{
				/*foreach (CGlobal::$my_server as $server){//Tạo lại file js cho chuyên mục
					@fopen("http://$server/catgen.php","r");
				}*/
				// @fopen(WEB_ROOT . "seo.php", "r");
			}
		}
		else{
			CGlobal::$allNewsCategories = AZArrCache::$arr_cache['allNewsCategories'];
			AZArrCache::$arr_cache 	= array();
		}
	}
	
    static function getWebsiteLogo($delcache = false) {
        if (CGlobal::$websiteLogo === false || (is_array(CGlobal::$websiteLogo) && !count(CGlobal::$websiteLogo)) || $delcache) 
        {
            if (AZArrCache::is_not_cached('websiteLogo', 0, '', $delcache)) 
            {
                if (!$delcache) {
                    CGlobal::$websiteLogo['current'] = array('id' => 0,
										                        //'img_src' => 'style/img/header/logo.png',
										                        'img_src' => 'style/img/header_new/logo.png',
										                        'title' => 'Trang chủ',
										                        'expired' => ''
										                    );

                    // For logo management
                    $re = DB::query("SELECT * FROM website_logo ORDER BY start_date DESC, end_date DESC");

                    if ($re) {
                        $logos = array();
                        $active = false;
                        while ($row = mysql_fetch_assoc($re))
                        {
                            if(isset(CGlobal::$img_server[$row['img_server']]))
                            {
	                        	$row['img_src'] = CGlobal::$img_server[$row['img_server']] . UP_FOLDER . '/' . $row['image'];
	                         
	                            if ($row['status'])
	                                $row['active'] = "Active";
	                            if ($row['start_date'])
	                                $row['startDate'] = date('d-m-Y', $row['start_date']);
	                            if ($row['end_date'])
	                                $row['endDate'] = date('d-m-Y', $row['end_date']);
	                            $logos[$row['id']] = $row;
	
	                            // Chọn logo theo sự kiện, hoạt động nào đó của AnhNghĩa
	                            if ($row['status'] && !$active) { // Nếu trạng thái của logo là đang active và chưa có logo nào được chọn
	                                if (!$row['start_date'] || ($row['start_date'] < TIME_NOW)) {
	                                    if (!$row['end_date'] || ($row['end_date'] >= TIME_NOW)) {
	                                        $active = true;
	                                    }
	                                }
	
	                                if ($active) {
	                                    CGlobal::$websiteLogo['current'] = array(
	                                        'id' => $row['id'],
	                                        'img_src' => CGlobal::$img_server[$row['img_server']] . UP_FOLDER . '/' . $row['image'],
	                                        'title' => AZLib::remove_4_js(AZLib::trimSpace(AZLib::plainText(addslashes($row['title'])))),
	                                        'expired' => $row['end_date']
	                                    );
	                                    DB::query("UPDATE website_logo SET status = 0 WHERE id <> " . $row['id']);
	                                }
	                            }
                            }
                        }

                        CGlobal::$websiteLogo['logos'] = $logos;

                        AZArrCache::set(array('websiteLogo' => CGlobal::$websiteLogo));
                    }
                }
            } else {
                CGlobal::$websiteLogo = AZArrCache::$arr_cache['websiteLogo'];
                AZArrCache::$arr_cache = array();
            }
        }
    }

    static function getProvinces($update_cache = 0, $delcache = false) {
        if (!CGlobal::$provinces || $delcache || $update_cache) {
            if (AZArrCache::is_not_cached('provinces_arr', 0, '', $delcache)) {
                if (!$delcache) {
                    $re = DB::query('SELECT id, name, brief_name, status, area FROM province ORDER BY position', __LINE__ . __FILE__);

                    $topProvinces = array();
                    $ortherProvinces = array();

                    if ($re) {
                        while ($province = mysql_fetch_assoc($re)) {
                            $province['ebname'] = AZLib::safe_title($province['name']);
                            if ($province['status'] == "HOME") {
                                $topProvinces[$province['id']] = $province;
                            } else {
                                $ortherProvinces[$province['id']] = $province;
                            }
                        }
                    }
                    $topProvinces[0] = array(
                        'id' => 0,
                        'name' => 'Toàn quốc',
                        'brief_name' => 'Toàn quốc',
                        'status' => 'SHOW',
                        'area' => '1',
                        'ebname' => 'Toan-Quoc',
                    );
                    CGlobal::$provinces = $topProvinces + $ortherProvinces;

                    AZArrCache::set(CGlobal::$provinces);
                } else {
                    foreach (CGlobal::$my_server as $server) {//Tạo lại file js cho city
                        @fopen("http://$server/citygen.php", "r");
                    }
                    $js_ver = rand(1, 1000);
                    AZMemcache::do_put("city_ver:", $js_ver);
                }
            } else {
                CGlobal::$provinces = AZArrCache::$arr_cache;
                AZArrCache::$arr_cache = array();
            }
        }
    }

    /* ------------------------------------------------------------------------- */

    // Sets a cookie, abstract layer allows us to do some checking, etc
    /* ------------------------------------------------------------------------- */
    static function my_setcookie($name, $value = "", $expires="") {
        $expires = ($expires) ? $expires : time() + 60 * 60 * 24 * 365;

        if (eregi(WEB_DOMAIN, $_SERVER['HTTP_HOST'])) {
            setcookie($name, $value, $expires, "/", '.'.WEB_DOMAIN);
        } else {
            setcookie($name, $value, $expires, "/");
        }
        $_COOKIE[$name] = $value;
    }

    static function subString($str, $start, $num, $ext=false) {
        $str = AZLib::plainText($str);

        if ($num > strlen($str) - $start)
            $num = strlen($str) - $start;

        if ($num <= 0)
            return '';

        $pos = strpos(substr($str, $start + $num + 1, strlen($str) - $start - $num - 1), ' ');

        $st = substr($str, $start, $num + $pos + 1);

        if ($ext && strlen($str) - $start > $num)
            $st.='..';

        return $st;
    }

    static function strippedLink($str, $length=68) {
        if ((strlen($str) - $length ) < 3) {
            return $str;
        }
        return substr($str, 0, floor(($length - 3) / 2)) . '...' . substr($str, -floor(($length - 3) / 2));
    }

    // ham tao descprtion trong tag DESCRIPTION
    static function descriptionText($str) {
        $meta_desc = AZLib::post_db_parse_html($str);
        $meta_desc = AZLib::plainText(html_entity_decode($meta_desc, ENT_QUOTES, "UTF-8"));
        $meta_desc = str_replace('\'', '', $meta_desc);
        $meta_desc = str_replace('"', '', $meta_desc);
        return AZLib::delDoubleSpace(AZLib::trimSpace($meta_desc));
    }

    static function plainText($str) {
        $arr_replace = array(
            '/\<p (.+?)\>(.+?)\<\/p\>/is' => '$2' . ' ',
            '/\<br \/\>/is' => ' ',
            '/\<br\>/is' => ' '
        );

        $str = preg_replace(array_keys($arr_replace), $arr_replace, $str);
        $str = strip_tags($str);

        //$filter = "\$|,,|@|\!|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\$|\.";
        //$filter = "\$|,,|@|\!|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\$|\.\.";
        //$str = preg_replace("/$filter/is", " ", $str);

        return self::delDoubleSpace(self::trimSpace(str_replace(array(chr(13), chr(9), chr(10), chr(239)), " ", $str)));
    }

    static function buttonDel($url, $imageFile, $title=false, $alt=false, $target=false, $admin=false) {
        if ($admin) {
            if (!User::is_admin())
                return '';
        }
        $st = '&nbsp;<a href= "' . $url . '" onclick="return confirm(\'Bạn có chắc chắn muốn xóa không!?\');"';
        if ($target)
            $st.= ' target="' . $target . '"';
        if ($title)
            $st.= ' title=" ' . addslashes($title) . '"';
        if ($alt)
            $st.= ' alt=" ' . addslashes($alt) . '"';
        $st .= '>' . '<img src="' . $imageFile . '" border="0"></a>';

        return $st;
    }

    static function button($url,$imageFile,$title=false,$alt=false,$target=false,$permiss=false,$admin=false,$popup=false){
		$st = '';
		if($popup){
			$st .=  '<img style="cursor:pointer;" src="'.$imageFile.'" '.Url::open_popup($url,800,600,false,false,false,false,false,1,1).' border="0">';
		}
		else {
			$st='<a href= "'.$url.'"';
			if($target)
			$st.=  ' target="'.$target.'"';
			if($title)
			$st.=  ' title=" '.addslashes($title).'"';
			if($alt)
			$st.=  ' alt=" '.addslashes($alt).'"';
			$st .=  '><img src="'.$imageFile.'" border="0"></a>';
		}
		
		if($admin){
			if(!User::isAdmin())
			return '';
		}
		elseif($permiss){
			if(!User::havePermission($permiss))
			return '';
		}
		return $st;
	}

	static function isPopup()
	{
		return isset($_REQUEST['is_popup']);
	}
	
	static function closePopup($js=true,$alert='',$return=false)
	{
		if($js)
		$str="<script> ";
		if($alert!='')
		$str.="alert('".$alert."'); ";
		$str.="window.close(); ";
		if($js)
		$str.="</script>";
		if($return)
		 	return $str;
		else 
			echo $str;
	}
	
	static function refreshParent($js=true,$alert='',$close=false,$return=false)
	{
		if($js)
		$str="<script> ";
		if($alert!='')
		$str.="alert('".$alert."');";
		$str.="window.opener.document.location.reload();";
		if($close!='')
		$str.="window.close(); ";
		if($js)
		$str.="</script>";
		if($return)
		 	return $str;
		else 
			echo $str;
	}
	
//	$mode 0:fit in, 1: fit top out, 2: fit out
    static function getImageSrc($imagePath, $width=0, $height=0, $itemTitle='', $siteTitle='', $mode=0, $limit_size=0, $server_no=0) 
    {
        return CGlobal::$img_server[$server_no] . 'thumb.php?src=' . $imagePath . '&w=' . $width . '&h=' . $height . '&t=' . urlencode($itemTitle) . '&s=' . urlencode($siteTitle) . ($mode ? '&m=' . (int) $mode : '') . ($limit_size ? '&lm=' . (int) $limit_size : '');
    }

    static function getImageThumb($imagePath, $width=0, $height=0, $limit_size=0, $server_no=0)
    {
    	if($imagePath && isset(CGlobal::$img_server[$server_no]) && CGlobal::$img_server[$server_no])
    	{
	        if ($width && $height)
	            return CGlobal::$img_server[$server_no] . "thumb/{$width}_$height/$imagePath";
	        elseif ($width) {
	            if ($limit_size)
	                return CGlobal::$img_server[$server_no] . "thumb_wl/{$width}/$imagePath";
	            else
	                return CGlobal::$img_server[$server_no] . "thumb_w/{$width}/$imagePath";
	        }
    	}
    	return '';
    }

    static function getImageThumbIn($imagePath, $width, $height, $server_no=0) 
    {
    	if($imagePath && isset(CGlobal::$img_server[$server_no]) && CGlobal::$img_server[$server_no])
    	{
    		return CGlobal::$img_server[$server_no] . "thumb_in/{$width}_$height/$imagePath";
    	}
    	return '';
    }

    static function base64_url_encode($input) {
        return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
    }

    static function getImageThumbMax($imagePath, $title='', $full_with_domain=true, $server_no=0)
    {
    	if($imagePath && isset(CGlobal::$img_server[$server_no]) && CGlobal::$img_server[$server_no])
    	{
	        if ($title != '') {
	            $title = ($title ? AZLib::base64_url_encode(str_replace(array('"', "'"), array('&quot;', '\\\''), stripslashes($title))) : '');
	            $file_ext = AZLib::getExtension($imagePath);
	            $imagePath = dirname($imagePath) . '/' . basename($imagePath, $file_ext) . ',' . $title . $file_ext;
	        }
	        //return ($full_with_domain?'http://'.IMAGE_PATH:'')."thumb_max/1200_800/$imagePath";
	        return ($full_with_domain ? CGlobal::$img_server[$server_no] : '') . "thumb_max/$imagePath";
    	}
    	return '';
    }

    static function _name_cleaner($name, $replace_string="_") {
        return preg_replace("/[^a-zA-Z0-9\-\_]/", $replace_string, $name);
    }

    static function make_safe_name($name, $replace_string="_") {
        return preg_replace("/[^\w\.]/", $replace_string, $name);
    }

    static function ftp_image_connect($server_no = 0)
    {
    	if(UP_TYPE == 'file')
    	{
    		return true;
    	}
    	elseif(UP_TYPE == 'ftp')
    	{
	        if (!(isset(CGlobal::$ftp_image_connect_id[$server_no]) && CGlobal::$ftp_image_connect_id[$server_no]))
	        {
	            if(isset(CGlobal::$img_ftp_server[$server_no]['host'], CGlobal::$img_ftp_server[$server_no]['user'], CGlobal::$img_ftp_server[$server_no]['pass']))
	            {
	                CGlobal::$ftp_image_connect_id[$server_no] = ftp_connect(CGlobal::$img_ftp_server[$server_no]['host']);
	
	                if (CGlobal::$ftp_image_connect_id[$server_no]) {
	                    // Login to FTP Server
	                    $login_result = ftp_login(CGlobal::$ftp_image_connect_id[$server_no], CGlobal::$img_ftp_server[$server_no]['user'], CGlobal::$img_ftp_server[$server_no]['pass']);
	                    if ($login_result) {
	                        // turn passive mode on
	                        ftp_pasv(CGlobal::$ftp_image_connect_id[$server_no], true);
	                        return true;
	                    }
	                    return false;
	                }
	            }
	            
	            return false;
	        }
	        
	        return true;
        }
    }

    static function ftp_image_close()
    {
    	if(UP_TYPE == 'file')
    	{
    		return true;
    	}
    	elseif(UP_TYPE == 'ftp')
    	{
	        foreach (CGlobal::$img_ftp_server as $server_no => $server) {
	            if (isset(CGlobal::$ftp_image_connect_id[$server_no]) && CGlobal::$ftp_image_connect_id[$server_no]) {
	                ftp_close(CGlobal::$ftp_image_connect_id[$server_no]);
	                CGlobal::$ftp_image_connect_id[$server_no] = false;
	            }
	        }
        }
    }

    static function ftp_image_put_file($destFileName, $sourceFileName, $server_no = 0, $mode=FTP_BINARY) 
    {
    	if(UP_TYPE == 'file')
    	{
    		return copy($sourceFileName, UP_PATH . UP_FOLDER . "/$destFileName");
    	}
    	elseif(UP_TYPE == 'ftp')
    	{
			if (AZLib::ftp_image_connect($server_no))//Upload via FTP
			{
				$destFileName = UP_FOLDER . "/$destFileName";
				
	            if (@ftp_put(CGlobal::$ftp_image_connect_id[$server_no], $destFileName, $sourceFileName, $mode)) {
	                @ftp_chmod(CGlobal::$ftp_image_connect_id[$server_no], 0777, $destFileName);
	                return true;
	            }
	            return false;
	        }
        }
    }

    static function ftp_image_delete_file($sourceFileName, $server_no = 0)
    {
    	if(UP_TYPE == 'file')
    	{
    		@unlink(UP_PATH.UP_FOLDER . "/ $sourceFileName");
    		
    		return true;
    	}
    	elseif(UP_TYPE == 'ftp')
    	{
	        if (AZLib::ftp_image_connect($server_no))
	        {
	        	$sourceFileName = UP_FOLDER . "/$sourceFileName";
	        	
	            if (ftp_delete(CGlobal::$ftp_image_connect_id[$server_no], $sourceFileName))
	            {
	                return true;
	            }
	            return false;
	        }
        }
    }

    static function ftp_check_dir($remote_dir_path, $mkdir=true, $server_no = 0) {
        $ret = true;
        
        if(UP_TYPE == 'file')
    	{
    		return self::CheckDir(UP_PATH . UP_FOLDER . "/$remote_dir_path");
    	}
    	elseif(UP_TYPE == 'ftp')
    	{
	        if (self::ftp_image_connect($server_no))
	        {
	        	$remote_dir_path = UP_FOLDER . "/$remote_dir_path";
	        	
	            if ($remote_dir_path == '')
	                return true;
	
	            $dir = split("/", $remote_dir_path);
	            $remote_dir_path = "";
	
	            for ($i = 0; $i < count($dir); $i++) {
	                if ($dir[$i] != '') {
	                    $remote_dir_path.="/" . $dir[$i];
	                    if (!@ftp_chdir(CGlobal::$ftp_image_connect_id[$server_no], $remote_dir_path)) {
	                        if ($mkdir) {
	                            @ftp_chdir(CGlobal::$ftp_image_connect_id[$server_no], "/");
	
	                            if (!@ftp_mkdir(CGlobal::$ftp_image_connect_id[$server_no], $remote_dir_path)) {
	                                $ret = false;
	                                break;
	                            }
	                        } else {
	                            $ret = false;
	                            break;
	                        }
	                    }
	                }
	            }
	            
	            @ftp_chdir(CGlobal::$ftp_image_connect_id[$server_no], "/");
	        } 
	        else 
	        {
	            $ret = false;
	        }
        }
        
        return $ret;
    }

    //Hàm chia thư mục ảnh!
    static function folderUpload($userid = 0, $folder = 'item') {//$folder: item, avatar, _common, category
        if (!$userid)
            $userid = User::id();

        if ($folder == '')
            $folder = 'item';

        return $folder . '/' .date('Y/m/', TIME_NOW) . round($userid / 1000) . "/$userid/";
    }

    static function convertUnicodeCase($test) {
        $uppercase_utf8 = array("A", "Á", "À", "Ả", "Ã", "Ạ", "Â", "Ấ", "Ầ", "Ẩ", "Ẫ", "Ậ", "Ă", "Ắ", "Ằ", "Ẳ", "Ẵ", "Ặ", "E", "É", "È", "Ẻ", "Ẽ", "Ẹ", "Ê", "Ế", "Ề", "Ể", "Ễ", "Ệ", "I", "Í", "Ì", "Ỉ", "Ĩ", "Ị", "O", "Ó", "Ò", "Ỏ", "Õ", "Ọ", "Ô", "Ố", "Ồ", "Ổ", "Ỗ", "Ộ", "Ơ", "Ớ", "Ờ", "Ở", "Ỡ", "Ợ", "U", "Ú", "Ù", "Ủ", "Ũ", "Ụ", "Ư", "Ứ", "Ừ", "Ử", "Ữ", "Ự", "Y", "Ý", "Ỳ", "Ỷ", "Ỹ", "Ỵ", "Đ", " ", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "+", "=", "|", "\\", "{", "}", ":", ";", "<", ">", "/", "?");
        $lowercase_utf8 = array("a", "á", "à", "ả", "ã", "ạ", "â", "ấ", "ầ", "ẩ", "ẫ", "ậ", "ă", "ắ", "ằ", "ẳ", "ẵ", "ặ", "e", "é", "è", "ẻ", "ẽ", "ẹ", "ê", "ế", "ề", "ể", "ễ", "ệ", "i", "í", "ì", "ỉ", "ĩ", "ị", "o", "ó", "ò", "ỏ", "õ", "ọ", "ô", "ố", "ồ", "ổ", "ỗ", "ộ", "ơ", "ớ", "ờ", "ở", "ỡ", "ợ", "u", "ú", "ù", "ủ", "ũ", "ụ", "ư", "ứ", "ừ", "ử", "ữ", "ự", "y", "ý", "ỳ", "ỷ", "ỹ", "ỵ", "đ", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
        if (!$test) {
            return $test;
        } else {
            $new_test = str_replace($uppercase_utf8, $lowercase_utf8, $test);
            return $new_test;
        }
    }

    //added by Nova....29.09.08 xu ly cac ky tu dac biet ngoai trang list
    static function filter_title($str)
    {
        $str = AZLib::post_db_parse_html($str);
        $filter = "\$|,,|@|\!|#|~|`|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\'|\"|\<|\>|\?|\||\\|\.\.|►|◄|♥|♣|♫|♩|©|∞|æ|Æ|å|Å|≈|Ä|ä|„|β|¦|•|∩|Ç|ç|¸|¢|χ|ˆ|♣|©|¤|†|‡|↓|°|Δ|δ|♦|÷|ε|≡|η|ð|ë|Ë|€|ƒ|½|¼|¾|⁄|Γ|γ|≥|>|↔|…|î|Î|∞|∫|ι|¿|Ï|ï|κ|λ|Λ|«|←|“|”|≤|◊|‹|‘|’|<|¯|—|µ|·|μ|–|≠|¬|ñ|Ñ|ν|Œ|œ|‾|ω|Ω|ª|º|Ø|ø|Ö|ö|¶|∂|‰|φ|Φ|Π|π|ϖ|±|£|∏|ψ|Ψ|√|»|→|®|ρ|›|Š|š|§|Σ|σ|ς|♠|∑|¹|²|³|ß|τ|Θ|θ|ϑ|Þ|þ|˜|×|™|↑|û|Û|¨|ϒ|υ|ü|Ü|ξ|Ξ|¥|ÿ|Ÿ|ζ";

        //æ|Æ||å|Å|≈|Ä|ä|„|β|¦|•|∩|Ç|ç|¸|¢|χ|ˆ|♣|©|¤|†|‡|↓|°|Δ|δ|♦|÷|ε|≡|η|ð|ë|Ë|€|ƒ|½|¼|¾|⁄|Γ|γ|≥|>|↔|…|î|Î|∞|∫|ι|¿|Ï|ï|κ|λ|Λ|«|←|“|≤|◊|‹|‘|<|¯|—|µ|·|μ|–|≠|¬|ñ|Ñ|ν|Œ|œ|‾|ω|Ω|ª|º|Ø|ø|Ö|ö|¶|∂|‰|φ|Φ|Π|π|ϖ|±|£|∏|ψ|Ψ|√|»|→|”|®|ρ|›|’|Š|š|§|Σ|σ|ς|♠|∑|¹|²|³|ß|τ|Θ|θ|ϑ|Þ|þ|˜|×|™|↑|û|Û|¨|ϒ|υ|ü|Ü|ξ|Ξ|¥|ÿ|Ÿ|ζ

        $str = preg_replace("/$filter/is", " ", $str);
        return preg_replace('/^([%|\$|\s])+/', '', $str);
    }

    static function convertUnicodeCaseWithoutHtml($test) {
        $uppercase_utf8 = array("A", "Á", "À", "Ả", "Ã", "Ạ", "Â", "Ấ", "Ầ", "Ẩ", "Ẫ", "Ậ", "Ă", "Ắ", "Ằ", "Ẳ", "Ẵ", "Ặ", "E", "É", "È", "Ẻ", "Ẽ", "Ẹ", "Ê", "Ế", "Ề", "Ể", "Ễ", "Ệ", "I", "Í", "Ì", "Ỉ", "Ĩ", "Ị", "O", "Ó", "Ò", "Ỏ", "Õ", "Ọ", "Ô", "Ố", "Ồ", "Ổ", "Ỗ", "Ộ", "Ơ", "Ớ", "Ờ", "Ở", "Ỡ", "Ợ", "U", "Ú", "Ù", "Ủ", "Ũ", "Ụ", "Ư", "Ứ", "Ừ", "Ử", "Ữ", "Ự", "Y", "Ý", "Ỳ", "Ỷ", "Ỹ", "Ỵ", "Đ", "Q", "W", "R", "T", "U", "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M", "P");
        $lowercase_utf8 = array("a", "á", "à", "ả", "ã", "ạ", "â", "ấ", "ầ", "ẩ", "ẫ", "ậ", "ă", "ắ", "ằ", "ẳ", "ẵ", "ặ", "e", "é", "è", "ẻ", "ẽ", "ẹ", "ê", "ế", "ề", "ể", "ễ", "ệ", "i", "í", "ì", "ỉ", "ĩ", "ị", "o", "ó", "ò", "ỏ", "õ", "ọ", "ô", "ố", "ồ", "ổ", "ỗ", "ộ", "ơ", "ớ", "ờ", "ở", "ỡ", "ợ", "u", "ú", "ù", "ủ", "ũ", "ụ", "ư", "ứ", "ừ", "ử", "ữ", "ự", "y", "ý", "ỳ", "ỷ", "ỹ", "ỵ", "đ", "q", "w", "r", "t", "p", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m", "p");
        if (!$test) {
            return $test;
        } else {
            $new_test = str_replace($uppercase_utf8, $lowercase_utf8, $test);
            return $new_test;
        }
    }

    static function safe_title($text) {
        $text = AZLib::post_db_parse_html($text);
        $text = self::stripUnicode($text);
        $text = self::_name_cleaner($text, "-");
        $text = str_replace("----", "-", $text);
        $text = str_replace("---", "-", $text);
        $text = str_replace("--", "-", $text);
        $text = trim($text, '-');

        if ($text) {
            return $text;
        } else {
            return "enbac";
        }
    }

    static function convert_one_br($text) {
        /* $text = str_replace("<br /><br /><br /><br /><br />","<br />",$text);
          $text = str_replace("<br /><br /><br /><br />","<br />",$text);
          $text = str_replace("<br /><br /><br />","<br />",$text);
          $text = str_replace("<br /><br />","<br />",$text);

          $text = trim($text, '<br />'); */

        return $text;
    }

    static function stripUnicode($str) {
        if (!$str)
            return false;
        $marTViet = array("à", "á", "ạ", "ả", "ã", "â", "ầ", "ấ", "ậ", "ẩ", "ẫ", "ă",
            "ằ", "ắ", "ặ", "ẳ", "ẵ", "è", "é", "ẹ", "ẻ", "ẽ", "ê", "ề"
            , "ế", "ệ", "ể", "ễ",
            "ì", "í", "ị", "ỉ", "ĩ",
            "ò", "ó", "ọ", "ỏ", "õ", "ô", "ồ", "ố", "ộ", "ổ", "ỗ", "ơ"
            , "ờ", "ớ", "ợ", "ở", "ỡ",
            "ù", "ú", "ụ", "ủ", "ũ", "ư", "ừ", "ứ", "ự", "ử", "ữ",
            "ỳ", "ý", "ỵ", "ỷ", "ỹ",
            "đ",
            "À", "Á", "Ạ", "Ả", "Ã", "Â", "Ầ", "Ấ", "Ậ", "Ẩ", "Ẫ", "Ă"
            , "Ằ", "Ắ", "Ặ", "Ẳ", "Ẵ",
            "È", "É", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ề", "Ế", "Ệ", "Ể", "Ễ",
            "Ì", "Í", "Ị", "Ỉ", "Ĩ",
            "Ò", "Ó", "Ọ", "Ỏ", "Õ", "Ô", "Ồ", "Ố", "Ộ", "Ổ", "Ỗ", "Ơ"
            , "Ờ", "Ớ", "Ợ", "Ở", "Ỡ",
            "Ù", "Ú", "Ụ", "Ủ", "Ũ", "Ư", "Ừ", "Ứ", "Ự", "Ử", "Ữ",
            "Ỳ", "Ý", "Ỵ", "Ỷ", "Ỹ",
            "Đ");

        $marKoDau = array("a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"
            , "a", "a", "a", "a", "a", "a",
            "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e",
            "i", "i", "i", "i", "i",
            "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o"
            , "o", "o", "o", "o", "o",
            "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u",
            "y", "y", "y", "y", "y",
            "d",
            "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A"
            , "A", "A", "A", "A", "A",
            "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E",
            "I", "I", "I", "I", "I",
            "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O"
            , "O", "O", "O", "O", "O",
            "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U",
            "Y", "Y", "Y", "Y", "Y",
            "D");

        $str = str_replace($marTViet, $marKoDau, $str);
        return $str;
    }

    static function getExtension($file) {
        $pos = strrpos($file, '.');
        if (!$pos) {
            return false;
        }
        $str = substr($file, $pos, strlen($file));
        return strtolower($str);
    }

    static function getCategoriesTree($get_direct=false, $hide=false)
    {
        if (!CGlobal::$categoriesTree)
        {
            self::getCats();
            $categories = array();

            if ($get_direct)
            {
                $topcat 	= array();
                $subcatlv2 	= array();

                $sql = 'SELECT * FROM category';

                if ($hide) 
                {
                    $sql.=' WHERE status != "HIDE" AND category.ref_id = 0';
                }

                $sql.= ' ORDER BY parent_id, position';
                
                $re = DB::query($sql);
                if ($re) 
                {
                    while ($cat = mysql_fetch_assoc($re)) 
                    {
                        if ($cat['status'] == 'HIDE')
                            $cat['name'].=' (đã ẩn)';

                        
                        if ($cat['parent_id']) //if current category is sub categories level 2
                        {
                            $subcatlv2[$cat['parent_id']][$cat['id']] = $cat;
                        }
                        else//top category
                        {
                            $topcat[$cat['id']] = $cat;
                        }
                    }
                }

                $subcat = array();
                
                foreach ($topcat as $cat) 
                {
                    
                    if (isset($subcatlv2[$cat['id']]))// if current top category has sub category level 2
                    {
                        foreach ($subcatlv2[$cat['id']] as $sc)
                        {
                            $subcat[$sc['id']] = $sc;//if current sub category level 2
                        }
                        
                        $cat['childs'] 			= $subcat;
                        $categories[$cat['id']] = $cat;
                        
                        $subcat = array();
                    }
                }
            } 
            else 
            {
                if (CGlobal::$subCategories) 
                {
                    $subcat = CGlobal::$subCategories;

                    foreach ($subcat as $id => $sub_cat)
                    {
                        if (isset(CGlobal::$allCategories[$id])) 
                        {
                            $cat = CGlobal::$allCategories[$id];

                            if ($cat['ref_id'] == 0) 
                            {
                                $childs = array();

                                foreach ($sub_cat as $sid => $cat2) 
                                {
                                    if ($cat2['ref_id'] == 0) 
                                    {
                                        $childs[$sid] = $cat2;
                                    }
                                }

                                $cat['childs'] 	= $childs;
                                
                                $categories[$id] = $cat;
                            }
                        }
                    }
                }
            }

            CGlobal::$categoriesTree = $categories;
        }
        //echo "<pre>";
        //print_r(CGlobal::$categoriesTree);

        return CGlobal::$categoriesTree;
    }

    static function getParam($aVarName, $aVarAlt="") {
        $lVarName = @$_REQUEST[$aVarName];
        if (!Empty($lVarName)) {
            if (is_array($lVarName)) {
                $lReturnArray = array();
                foreach ($lVarName as $key => $value) {
                    $value = self::clean_value($value);
                    $key = self::clean_key($key);
                    $lReturnArray[$key] = $value;
                }
                return $lReturnArray;
            }
            else
                return self::clean_value($lVarName); // Clean input and return it




        }
        else
            return $aVarAlt;
    }

    static function cleanHtml($aVarName, $aVarAlt="") {
        $lVarName = $aVarName;
        if (!Empty($lVarName)) {
            if (is_array($lVarName)) {
                $lReturnArray = array();
                foreach ($lVarName as $key => $value) {
                    $value = self::clean_value($value);
                    $key = self::clean_key($key);
                    $lReturnArray[$key] = $value;
                }
                return $lReturnArray;
            }
            else
                return self::clean_value($lVarName); // Clean input and return it




        }
        else
            return $aVarAlt;
    }

    function getParamInt($aVarName, $aVarAlt=0) {
        $lNum = 0;
        if ($aVarName) {
            if (isset($_POST[$aVarName]))
                $lNum = $_POST[$aVarName];
            elseif (isset($_GET[$aVarName]))
                $lNum = $_GET[$aVarName];
            else
                $lNum = $aVarAlt;
        }

        return (int) $lNum;
        //return (int)preg_replace('/\D+/', '', $lNum);
    }

    /* ------------------------------------------------------------------------- */

    // Key Cleaner - ensures no funny business with form elements
    /* ------------------------------------------------------------------------- */
    static function clean_key($key) {
        if ($key == "") {
            return "";
        }

        $key = htmlspecialchars(urldecode($key));
        $key = preg_replace("/\.\./", "", $key);
        $key = preg_replace("/\_\_(.+?)\_\_/", "", $key);
        $key = preg_replace("/^([\w\.\-\_]+)$/", "$1", $key);
        return $key;
    }

    /* ------------------------------------------------------------------------- */

    // Clean value
    /* ------------------------------------------------------------------------- */

    static function clean_value($val) {
        $strip_space_chr = 1;
        $get_magic_quotes = @get_magic_quotes_gpc();

        if ($val == "") {
            return "";
        }

        $val = str_replace("&#032;", " ", $val);

        if ($strip_space_chr) {
            $val = str_replace(chr(0xCA), "", $val);  //Remove sneaky spaces
        }
        //$val = str_replace( "&"            , "&amp;"         , $val );
        $val = str_replace("<!--", "", $val); //&#60;&#33;--
        $val = str_replace("-->", "", $val); //--&#62;
        $val = preg_replace("/<script/i", "&#60;script", $val);
        $val = str_replace(">", "&gt;", $val);
        $val = str_replace("<", "&lt;", $val);
        $val = str_replace("\"", "&quot;", $val);
        //$val = preg_replace( "/\n/"        , "<br />"        , $val ); // Convert literal newlines
        $val = preg_replace("/\\\$/", "&#036;", $val);
        $val = preg_replace("/\r/", "", $val); // Remove literal carriage returns
        $val = str_replace("!", "&#33;", $val);
        $val = str_replace("'", "&#39;", $val); // IMPORTANT: It helps to increase sql query safety.

        if ($get_magic_quotes) {
            $val = stripslashes($val);
        }

        $val = preg_replace("/\\\(?!&amp;#|\?#)/", "&#092;", $val);

        return $val;
    }

    //-----------------------------------------
    // parse_html
    // Converts the doHTML tag
    //-----------------------------------------
    static function post_db_parse_html($t="") {
        if ($t == "") {
            return $t;
        }

        //-----------------------------------------
        // Remove <br>s 'cos we know they can't
        // be user inputted, 'cos they are still
        // &lt;br&gt; at this point :)
        //-----------------------------------------

        /* 		if ( $this->pp_nl2br != 1 )
          {
          $t = str_replace( "<br>"    , "\n" , $t );
          $t = str_replace( "<br />"  , "\n" , $t );
          } */

        $t = str_replace("&#39;", "'", $t);
        $t = str_replace("&#33;", "!", $t);
        $t = str_replace("&#036;", "$", $t);
        $t = str_replace("&#124;", "|", $t);
        $t = str_replace("&amp;", "&", $t);
        $t = str_replace("&gt;", ">", $t);
        $t = str_replace("&lt;", "<", $t);
        $t = str_replace("&quot;", '"', $t);

        //-----------------------------------------
        // Take a crack at parsing some of the nasties
        // NOTE: THIS IS NOT DESIGNED AS A FOOLPROOF METHOD
        // AND SHOULD NOT BE RELIED UPON!
        //-----------------------------------------

        $t = preg_replace("/javascript/i", "j&#097;v&#097;script", $t);
        $t = preg_replace("/alert/i", "&#097;lert", $t);
        $t = preg_replace("/about:/i", "&#097;bout:", $t);
        $t = preg_replace("/onmouseover/i", "&#111;nmouseover", $t);
        $t = preg_replace("/onmouseout/i", "&#111;nmouseout", $t);
        $t = preg_replace("/onclick/i", "&#111;nclick", $t);
        $t = preg_replace("/onload/i", "&#111;nload", $t);
        $t = preg_replace("/onsubmit/i", "&#111;nsubmit", $t);
        $t = preg_replace("/object/i", "&#111;bject", $t);
        $t = preg_replace("/frame/i", "fr&#097;me", $t);
        $t = preg_replace("/applet/i", "&#097;pplet", $t);
        $t = preg_replace("/meta/i", "met&#097;", $t);
        $t = preg_replace("/embed/i", "met&#097;", $t);

        return $t;
    }

    static function word_limit($string, $length, $ellipsis="...") {
        return (count($words = explode(' ', $string)) > $length) ? implode(' ', array_slice($words, 0, $length)) . $ellipsis : $string;
    }

    static function remove_4_js($t) {
        $t = self::make_single_space($t);
//		$t = str_replace( "'","&#39;"  ,  $t );
        $t = str_replace("'", "&quot;", $t);
        $t = str_replace("&#39;", "", $t);
        $t = str_replace("!", "&#33;", $t);
        $t = str_replace("$", "&#036;", $t);
        $t = str_replace("|", "&#124;", $t);
        //$t = str_replace( "&","&amp;"   , $t );
        $t = str_replace(">", "&gt;", $t);
        $t = str_replace("<", "&lt;", $t);
        $t = str_replace('"', "&quot;", $t);
        //$t = str_replace( '"', "&quot;" , $t );

        $t = str_replace(chr(10), "", $t);
        $t = str_replace(chr(13), "", $t);

        return trim($t);
    }

    static function make_single_space($t="") {
        if ($t == "") {
            return;
        }
        return eregi_replace("[[:space:]]+", " ", $t);
    }

    static function CheckDir($pDir, $check_memcache = false) {
        if (!$check_memcache) {
            if (is_dir($pDir))
                return true;
            if (!@mkdir($pDir, 0777, true)) {
                return false;
            }
            self::chmod_dir($pDir, 0777);
        }
        return true;
    }

    static function chmod_dir($dir, $mod=0777) {
        $parent_dir = dirname(str_replace(ROOT_PATH, '', $dir));
        if ($parent_dir != '' && $parent_dir != '.') {
            //echo $parent_dir.'/<br />';
            @chmod($dir, $mod);
            self::chmod_dir($parent_dir, $mod);
        }
        return true;
    }

    static function catPath($catid) {
        self::getCats();
        if ($catid && isset(CGlobal::$allCategories[$catid])) {
            $cat_path = '<a href="' . Url::build('home', false) . '">Trang chủ</a>';

            $current_cat = CGlobal::$allCategories[$catid];

            if ($current_cat['parent_id']) {
                if (isset(CGlobal::$allCategories[$current_cat['parent_id']]))
                    $cat_path.=' > <a href="' . Url::build('list_detail', array('category_id' => $current_cat['parent_id'], 'type')) . '">' . stripslashes(CGlobal::$allCategories[$current_cat['parent_id']]['name']) . '</a> > <a href="' . Url::build('list_detail', array('category_id' => $current_cat['id'], 'type')) . '"><font color="#D8C219">' . stripslashes($current_cat['name']) . '</font></a>';
                else
                    $cat_path.=' > <a href="' . Url::build('list_detail', array('category_id' => $current_cat['id'], 'type')) . '"><font color="#D8C219">' . stripslashes($current_cat['name']) . '</font></a>';
            }
            else {
                $cat_path.=' > <a href="' . Url::build('list_detail', array('category_id' => $current_cat['id'], 'type')) . '"><font color="#D8C219">' . stripslashes($current_cat['name']) . '</font></a>';
            }
        } else {
            $cat_path = '<a href="' . Url::build('home', false) . '"><font color="#D8C219">Trang chủ</font></a>';
        }
        return $cat_path;
    }

    static function titlePath($catid) {
        self::getCats();
        if ($catid && isset(CGlobal::$allCategories[$catid])) {
            $title_path = '';

            $current_cat = CGlobal::$allCategories[$catid];

            if ($current_cat['parent_id']) {
                if (isset(CGlobal::$allCategories[$current_cat['parent_id']]))
                    $title_path.=stripslashes($current_cat['name']) . ' - ' . stripslashes(CGlobal::$allCategories[$current_cat['parent_id']]['name']);
                else
                    $title_path.=stripslashes($current_cat['name']);
            }
            else {
                $title_path .= stripslashes($current_cat['name']);
            }
        } 

        return $title_path;
    }

    static function getOption($options_array, $selected) {
        $input = '';
        if ($options_array)
            foreach ($options_array as $key => $text) {
                $input .= '<option value="' . $key . '"';
                if ($key === '' && $selected === '') {
                    $input .= ' selected';
                } else
                if ($selected !== '' && $key == $selected) {
                    $input .= ' selected';
                }
                $input .= '>' . $text . '</option>';
            }
        return $input;
    }

    static function getOptionMulti($options, $select_array) {
        $input = '';
        if ($options) {
            foreach ($options as $key => $text) {
                $input .= '<option value="' . $key . '"';
                if (in_array($key, $select_array)) {
                    $input .= ' selected';
                }

                $input .= '>' . $text . '</option>';
            }
        }
        return $input;
    }

    static function getOptionNum($min, $max, $default=1) {
        $options = '';
        for ($i = $min; $i <= $max; $i++) {
            $options .= '<option value="';
            if ($i < 10)
                $options .= '0' . $i . '"';
            else
                $options .= $i . '"';
            if ($i == $default) {
                $options .= ' selected';
            }
            $options .= '>' . $i . '</option>';
        }
        return $options;
    }

    static function InserMessage($ArrValue, $arrID, $status='inbox') {
        if ($status == 'sent') {
            $ArrValue["mt_owner_id"] = $arrID[0];
            $ArrValue["mt_owner_name"] = $arrID[1];
            $ArrValue["mt_from_id"] = $arrID[2];
        } elseif ($status == 'inbox') {
            $ArrValue["mt_owner_id"] = $arrID[2];
            $ArrValue["mt_owner_name"] = $arrID[3];
            $ArrValue["mt_from_id"] = $arrID[0];
            $ArrValue["mt_to_name"] = $arrID[1];
        }

        $ArrValue["mt_vid_folder"] = $status;
        return DB::insert('message_topics', $ArrValue, false, __LINE__ . __FILE__);
    }

    static function Send_pm($sender_id, $sender_name, $receiver_user, $title, $content, $once_way=false, $ref_id=0) {
        $num_send = 0;

        $new_row_msg = array(
            'msg_date' => TIME_NOW,
            'msg_post' => htmlspecialchars_decode($content),
            'msg_author_id' => $sender_id,
            'msg_author_name' => $sender_name,
            'msg_ip_address' => AZLib::ip()
        );

        // ***** CHÚ Ý *****
        // Newest = 0 - Mới nhất, = 1 - Cũ hơn (Do lỗi tạo giá trị mặc định trường này là 0, nên quy ước hơi bị ngược, để đỡ mất công chạy lệnh update database
        // ***** CHÚ Ý *****

        $msg_id = DB::insert('message_text', $new_row_msg);

        $inbox_ref_id = 0;
        if ($ref_id) {
            $msgText = DB::select('message_topics', 'mt_id = ' . $ref_id . ' AND mt_owner_id = ' . $sender_id);

            if ($msgText['mt_msg_id']) {
                // Kiểm tra xem người nhận còn tin nhắn gốc hay không
                $mtTopic = DB::select('message_topics', 'mt_msg_id = ' . $msgText['mt_msg_id'] . ' AND mt_id <> ' . $ref_id . ' AND mt_owner_id = ' . $receiver_user['id'] . ' AND mt_from_id <> ' . $receiver_user['id']);
                // Nế còn tin nhắn gốc
                if ($mtTopic['mt_id']) {
                    // Gán tin nhắn sắp gửi là tin nhắn mới nhất
                    // Lấy id tin nhắn gốc của người gửi làm ref_id cho tin nhắn sắp gửi
                    $inbox_ref_id = $mtTopic['mt_id'];
                }
            }
        }

        // Đặt cờ tin nhắn mới nhất (inbox) của các tin trong luồng của người nhận = 0
        if ($inbox_ref_id) {
            DB::query('UPDATE message_topics SET mt_newest = 1 WHERE mt_newest = 0 AND mt_vid_folder = \'inbox\' AND (mt_ref_id = ' . $inbox_ref_id . ' OR mt_id = ' . $inbox_ref_id . ') AND mt_owner_id = ' . $receiver_user["id"]);
        }

        // Đặt cờ tin nhắn mới nhất (sent) của các tin trong luồng của người gửi = 0
        if ($ref_id) {
            DB::query('UPDATE message_topics SET mt_newest = 1 WHERE mt_newest = 0 AND mt_vid_folder = \'sent\' AND (mt_ref_id = ' . $ref_id . ' OR mt_id = ' . $ref_id . ') AND mt_owner_id = ' . $sender_id);
        }

        $new_row_msg = array(
            'mt_msg_id' => $msg_id,
            'mt_date' => TIME_NOW,
            'mt_title' => $title,
            'mt_ref_id' => $inbox_ref_id,
            'mt_newest' => 0,
            'mt_to_name' => $receiver_user["user_name"],
            'mt_read' => 0
        );

        $arrID = array($sender_id,
            $sender_name,
            $receiver_user["id"],
            $receiver_user["user_name"]
        );

        // Tạo tiêu đề tin nhắn mới
        $msg_id_inbox = AZLib::InserMessage($new_row_msg, $arrID, $status = 'inbox');

        if ($msg_id_inbox) {
            $num_send++;

            //insert vao bang feed
            $feed_sql = "(4,{$receiver_user['id']},{$msg_id_inbox},{$new_row_msg['mt_date']},{$sender_id},0)";
            $feed_sql = "INSERT INTO feed (`type`,`user_id`,`ref_id`,`time`,`act_user_id`,`item_id`) VALUES " . $feed_sql;

            DB::query($feed_sql);
        }

        if ($once_way == false) {
            $new_row_msg['mt_read'] = 1;
            $new_row_msg['mt_ref_id'] = $ref_id;
            $msg_id_sent = AZLib::InserMessage($new_row_msg, $arrID, $status = 'sent');
            $num_send++;
        } else {
            $msg_id_sent = true;
        }

        // Nếu tin được tạo mới là tin nhắn trả lời
        //if($inbox_ref_id)
        //{
        // Đặt cờ đã có tin nhắn trả lời cho tin nhắn gốc trong cả "inbox" và "sent"
        //DB::query('	UPDATE message_topics SET mt_has_reply = 1 WHERE mt_id = ' . $ref_id . ' AND mt_vid_folder = \'inbox\'');
        //	DB::query('	UPDATE message_topics SET mt_has_reply = 1 WHERE mt_id = ' . $inbox_ref_id);
        //}

        if ($msg_id_inbox && $msg_id_sent) {
            $count_pm = true;
            // Đối với tin trả lời, chỉ đếm những tin trả lời mới cho tin thuộc các luồng tin khác nhau
            if ($ref_id) {
                // Kiểm tra xem trong luồng tin hiện tại có tin trả lời nào chưa đọc hay không
                $re = DB::query('SELECT COUNT(*) AS unreadCount FROM message_topics
								WHERE mt_ref_id = ' . $ref_id . ' 
									AND mt_vid_folder = \'inbox\' AND mt_owner_id = ' . $receiver_user["id"] . '
									AND mt_read = 0');
                if ($re) {
                    $row = mysql_fetch_assoc($re);
                    // Nếu có thì không tính thêm tin này vào tổng pm
                    if ($row['unreadCount'] > 1) {
                        $count_pm = false;
                    }
                }
            }
            if ($count_pm) {
                DB::query('UPDATE user SET total_pm = total_pm + 1 WHERE id=' . $receiver_user["id"]);
            }
            User::getUser($receiver_user["id"], 0, 1);
            DB::query("UPDATE message_text SET msg_sent_to_count = $num_send WHERE msg_id = $msg_id");

            if ($receiver_user['email'] && $receiver_user['email_alert']) {
                $link = WEB_ROOT . Url::build('message');
                $content = trim(addslashes(AZLib::parseBBCode($title . ' - ' . $content, true)));

                AZLib::addCronJob('pm', $content, $receiver_user['id'], User::user_name(), '', 0, '', $link);
            }

            return true;
        } else {
            return false;
        }
    }

    static function delete_messages($ids) {
        if (User::is_login() && $ids) {
            $rows_total = DB::count('message_topics', 'mt_id IN (' . $ids . ') AND mt_read = 0');
            DB::query('UPDATE user SET total_pm = total_pm-' . $rows_total ['total'] . ' WHERE id=' . User::id() . ' AND total_pm>0');
            User::getUser(User::id(), 0, 1);
            DB::query('DELETE FROM message_topics WHERE mt_id IN (' . $ids . ')');
            DB::query('DELETE FROM feed WHERE ref_id IN (' . $ids . ') AND type=4');
        }
    }

    static function deleteBadWord($id, $type) {
        return DB::query('DELETE FROM bad_content WHERE id_item = ' . $id . ' AND type = ' . $type, __LINE__ . __FILE__);
    }

    static function duration($duration) {
        if ($duration > 0) {
            $time = $duration;
            $year = floor($time / (365 * 3600 * 24));
            $month = floor($time / (30 * 3600 * 24));
            $week = floor($time / (7 * 3600 * 24));
            $day = floor($time / (3600 * 24));
            $hour = floor(($time % (3600 * 24)) / (3600));
            $minute = floor(($time % (3600)) / (60));

            if ($year != 0) {
                return $year . ' năm ';
            }

            if ($month != 0) {
                return $month . ' tháng ';
            }
            if ($week != 0) {
                return $week . ' tuần ';
            }
            if ($day != 0) {
                return $day . ' ngày ';
            }
            if ($hour != 0) {
                return $hour . ' giờ ';
            }

            if ($minute != 0) {
                return $minute . ' phút ';
            }

            return $time . ' giây ';
        } else {
            return ' vài giây';
        }
    }

    static function duration_time($time) {
        $time = TIME_NOW - $time;

        if ($time > 0) {
            if ($time > (365 * 86400)) {
                return floor($time / (365 * 86400)) . ' năm trước';
            }

            if ($time > (30 * 86400)) {
                return floor($time / (30 * 86400)) . ' tháng trước';
            }

            if ($time > (7 * 86400)) {
                return floor($time / (7 * 86400)) . ' tuần trước';
            }
            if ($time > 86400) {
                return floor($time / (86400)) . ' ngày trước';
            }

            if ($time > 3600) {
                return floor($time / (3600)) . ' giờ trước';
            }

            if ($time > 60) {
                return floor($time / (60)) . ' phút trước';
            }
        }
        return ' vài giây trước';
    }

    static function getTopItem($user_id) {
        $subDir = 'user_item/' . floor($user_id / 1000);

        $sql = 'SELECT id, name, category_id FROM item WHERE user_id=' . $user_id . ' AND status=1 ORDER BY up_time DESC LIMIT 0,5';
        return AZCache::cache($sql, __LINE__ . __FILE__, '600', 0, '', $subDir);
    }

    static function parseBBCode($text, $direct = false) {
        $old_text = $text;

        $text = stripslashes($text);

        //  $text = htmlspecialchars($text);
        //$text = nl2br($text);
        // First: If there isn't a "[" and a "]" in the message, don't bother.
        if (strpos($old_text, "[") !== false && strpos($old_text, "]") !== false) {
            $arr_replace = array(
                '/\[font\=(.*?)\](.+?)\[\/font\]/is' => '<span style="font-family: $1;">$2</span>',
                '/\[font\=(.*?)\](\s*)\[\/font\]/is' => '',
                '/\[size\=(.*?)\](.+?)\[\/size\]/is' => '<span style="font-size: $1;">$2</span>',
                '/\[size\=(.*?)\](\s*)\[\/size\]/is' => '',
                '/\[color\=(.*?)\](.+?)\[\/color\]/is' => '<span style="color: $1;">$2</span>',
                '/\[color\=(.*?)\](\s*)\[\/color\]/is' => '',
                //'/\[img\](.+?)\[\/img\]/is'     			=>  '<img src="$1" alt="Picture" border="0"/>',
                '/\[img\](.+?)\[\/img\]/is' => '',
                '/\[img\](\s*)\[\/img\]/is' => '',
                /* "/\\[b\\](.+?)\[\/b\]/is"					=>	'<b>$1</b>',
                  "/\\[b\\](\s*)\[\/b\]/is"					=>	'',
                  "/\\[i\\](.+?)\[\/i\]/is"					=>	'<i>$1</i>',
                  "/\\[i\\](\s*)\[\/i\]/is"					=>	'',
                  "/\\[u\\](.+?)\[\/u\]/is"					=>	'<u>$1</u>',
                  "/\\[u\\](\s*)\[\/u\]/is"					=>	'', */

                "/\\[b\\]/is" => '<b>',
                "/\\[\/b\]/is" => '</b>',
                "/\\[i\\]/is" => '<i>',
                "/\\[\/i\]/is" => '</i>',
                "/\\[u\\]/is" => '<u>',
                "/\\[\/u\]/is" => '</u>',
//          '/\[url\=(.*?)\](.*?)\[\/url\]/is'			=>	'<a href="$1" target="_blank" title="$2">$2</a>',
                '/\[url\=(.*?)\](.*?)\[\/url\]/is' => '<a href="$1" target="_blank">$2</a>',
//          '/\[url\](.*?)\[\/url\]/is'					=>	'<a href="$1" target="_blank">$1</a>',
                '/\[url\](.*?)\[\/url\]/is' => '<a href="$1" target="_blank">$1</a>',
                '/\[url\](\s*)\[\/url\]/is' => '',
//			'/\[img\](.*?)\[\/img\]/is' 				=>  '<img src="$1" border="0"/>',
                "/\[s\](.+?)\[\/s\]/is" => '<s>\1</s>',
                "/\[s\](\s*)\[\/s\]/is" => '',
                //"/\[quote\](.+?)\[\/quote\]/is"				=>	'<blockquote>$1</blockquote>',
                //"/\[quote\](\s*)\[\/quote\]/is"				=>	'',

                "/\[quote\]/is" => '<div class="block_mess_sub">',
                "/\[\/quote\]/is" => '</div>',
                "/\[hr\]/is" => '<hr>',
                "/\[dotter\]/is" => '<div style=" border-top:1px dotter #ccc">',
                "/\[\/dotter\]/is" => '</div>',
            );

            $text = preg_replace(array_keys($arr_replace), $arr_replace, $text);
            $text = eregi_replace("\\[color=([^\\[]*)\\]([^\\[]*)\\[/color\\]", "<font color=\"\\1\">\\2</font>", $text);
            //            $text = eregi_replace("\\[alink=([^\\[]*)\\]([^\\[]*)\\[/alink\\]","<a href=\"\\1\" target=\"_blank\" title=\"Liên kết\">\\2</a>",$text);
            $text = eregi_replace("\\[alink=([^\\[]*)\\]([^\\[]*)\\[/alink\\]", "<a href=\"\\1\" target=\"_blank\">\\2</a>", $text);
        }

        $emoticon_dir = ($direct ? WEB_ROOT : '') . 'style/images/emoticon/';

        $arr_replace = array(
            "/:x/is" => '<img alt=":x" title=":x" src="' . $emoticon_dir . 'envy.gif" />',
            "/:d/is" => '<img alt=":D" title=":D" src="' . $emoticon_dir . 'grin.gif" />',
            "/\\[clap\\]/is" => '<img alt="clap" title="clap" src="' . $emoticon_dir . 'clap.gif" />',
            "/:-\\*/is" => '<img alt=":-*" title=":-*" src="' . $emoticon_dir . 'love.gif" />',
            "/:\\+\\)/is" => '<img alt=":+)" title=":+)" src="' . $emoticon_dir . 'shy.gif" />',
            "/:-s/is" => '<img alt=":-S" title=":-S" src="' . $emoticon_dir . 'fear.gif" />',
            "/:-\\(/is" => '<img alt=":-(" title=":-(" src="' . $emoticon_dir . 'unhappy.gif" />',
            "/:-@/is" => '<img alt=":-@" title=":-@" src="' . $emoticon_dir . 'uplook.gif" />',
            "/:-&/is" => '<img alt=":-&" title=":-&" src="' . $emoticon_dir . 'puke.gif" />',
            "/:-\\//is" => '<img alt=":-/" title=":-/" src="' . $emoticon_dir . 'question.gif" />',
            "/:-o/is" => '<img alt=":-o" title=":-o" src="' . $emoticon_dir . 'shock.gif" />',
            "/I-\\)/is" => '<img alt="I-)" title="I-)" src="' . $emoticon_dir . 'sleepy.gif" />',
            "/\\[tea\\]/is" => '<img alt="[tea]" title="[tea]" src="' . $emoticon_dir . 'coffee.gif" />',
            "/:\\(\\(/is" => '<img alt=":((" title=":((" src="' . $emoticon_dir . 'cry.gif" />',
            "/:\\)/is" => '<img alt=":)" title=":)" src="' . $emoticon_dir . 'smile.gif" />',
            "/\\[-\\(/is" => '<img alt=":x" title=":x" src="' . $emoticon_dir . 'sweat.gif" />',
            "/X-\\(/is" => '<img alt=":x" title=":x" src="' . $emoticon_dir . 'anger.gif" />',
            "/:-bd/is" => '<img alt=":x" title=":x" src="' . $emoticon_dir . 'wub.gif" />',
            "/:hh/is" => '<img alt=":hh" title=":hh" src="' . $emoticon_dir . 'hamarneh.gif" />',
            "/\\[pig\\]/is" => '<img alt="[pig]" title="[pig]" src="' . $emoticon_dir . 'pig.gif" />',
            "/\\[shuai\\]/is" => '<img alt="[shuai]" title="[shuai]" src="' . $emoticon_dir . 'shuai.gif" />',
            "/\\[bad\\]/is" => '<img alt="[bad]" title="[bad]" src="' . $emoticon_dir . 'bad.gif" />',
            "/\\[smoke\\]/is" => '<img alt="[smoke]" title="[smoke]" src="' . $emoticon_dir . 'smoke.gif" />',
            "/\\[stupid\\]/is" => '<img alt="[stupid]" title="[stupid]" src="' . $emoticon_dir . 'stupid.gif" />',
            "/\\[ok\\]/is" => '<img alt="[ok]" title="[ok]" src="' . $emoticon_dir . 'ok.gif" />',
            "/\\[thumbdown\\]/is" => '<img alt="[thumbdown]" title="[thumbdown]" src="' . $emoticon_dir . 'thumbdown.gif" />',
            "/\\[kill\\]/is" => '<img alt="[kill]" title="[kill]" src="' . $emoticon_dir . 'kill.gif" />',
            "/\\[dog\\]/is" => '<img alt="[dog]" title="[dog]" src="' . $emoticon_dir . 'dog.gif" />',
            "/\\[cool\\]/is" => '<img alt="[cool]" title="[cool]" src="' . $emoticon_dir . 'cool.gif" />',
            "/\\[zan\\]/is" => '<img alt="[zan]" title="[zan]" src="' . $emoticon_dir . 'zan.gif" />',
        );

        $text = preg_replace(array_keys($arr_replace), $arr_replace, $text);

        unset($old_text);
        return $text;
        //        return self::BBCode($text);
    }

    static function BBCode($text) {
        $text = stripslashes($text);
        //  $text = htmlspecialchars($text);
        // $text = nl2br($text);

        $arr_replace = array(
            '/<b>(.+?)<\/b>/is' => '[b]$1[/b]',
            '/<i>(.+?)<\/i>/is' => '[i]$1[/i]',
            '/<u>(.+?)<\/u>/is' => '[u]$1[/u]',
            '/<a href="(.*?)" target="_blank">(.*?)<\/a>/is' => '[url=$1]$2[/url]',
            '/<a href="(.*?)">(.*?)<\/a>/is' => '[url=$1]$2[/url]',
            '/<s>(.+?)<\s>/is' => '[s]$1[/s]',
            '/<blockquote>(.+?)<\/blockquote>/is' => '[quote]$1[/quote]',
            '/<br \/>/is' => "\n",
            '/<br\/>/is' => "\n",
            '/<br>/is' => "\n",
            '/&lt;br&gt;/is' => "\n"
        );

        $text = preg_replace(array_keys($arr_replace), $arr_replace, $text);

        return $text;
    }

    function getListFriendofUser($user_id) {
        $sql = 'SELECT user_id_friend FROM `friends_list` WHERE user_id = "' . $user_id . '"';

        $str = '';
        $subDir = 'user/' . floor($user_id / 1000);
        if ($items = AZCache::cache($sql, __LINE__ . __FILE__, '1', 0, '', $subDir)) {
            foreach ($items as $value) {
                $str .= $value['user_id_friend'] . ",";
            }
        }
        return $str;
    }

    function showJqueryMessage($content, $header = '', $theme = 'default', $sticky = 'false') {
        echo '
			<script type="text/javascript">
			(function($){
	
				$(document).ready(function(){
	
					$.jGrowl("' . $content . '", {
						header  : 	\'' . $header . '\',
						opacity : 	\'hide\',
						
						sticky	: 	' . $sticky . ',
						theme  	:	\'' . $theme . '\'
				
					});
	
				});
			})(jQuery);
			</script>
		';
    }

    /**
     * Tập hợp các hành động của người dùng ( TuấnNK add 20080709 )
     * Chỉ cập nhật khi người dùng cập nhật thông tin nhận Email thông báo từ Hệ thống ( trường email_alert = 1 )
     * @param string $type : loại hành động ( item_comment -> Phản hồi sp, 	user_comment	-> Comment người dùng,
     * 										 bidding	  -> Đặt giá, 		friend 	  		-> chấp nhận kết bạn hàng,
     * 										 friend 	  -> kết bạn hàng,  de_friend 	  	-> từ chối kết bạn hàng,
     * 										 pm	   	 	  -> Gửi tin nhắn
     * @param string $title : Nội dung hành động, bao gồm html chứa link trong đó về hành động
     * @param string $content : Nội dung comment, lưu bút nếu có
     * @param int $user_id : id của user chủ thể
     * @param string $user_name : user_name của user chủ thể
     * @param int $relate_user_id : id của user được tác động ( nếu có )
     * @param string $relate_user_name : id của user được tác động ( nếu có )
     */
    static function addCronJob($type, $content='', $user_id, $user_name_act='', $user_email_act='', $ref_id=0, $ref_title='', $ref_link='') {
        $cron_job_arr = array(
            'type' => $type,
            'content' => $content,
            'user_id' => (int) $user_id,
            'user_name_act' => $user_name_act,
            'user_email_act' => $user_email_act,
            'ref_id' => $ref_id,
            'ref_title' => $ref_title,
            'ref_link' => $ref_link,
            'bid_price' => 0,
            'time' => TIME_NOW,
        );
        return DB::insert('cron_job', $cron_job_arr);

        /* $sql = "INSERT INTO cron_job (type, content, user_id,user_name_act,user_email_act,ref_id,ref_title,ref_link,bid_price,time) VALUES
          ('$type','$content','$user_id','$user_name_act','$user_email_act','$ref_id','$ref_title','$ref_link','$bid_price','".TIME_NOW."')
          ";
          return DB::query($sql); */
    }

    static function get_yahoo_avatar($yahoo_id, $user_id=0, $server_no = 0) {
        $cache_path = ROOT_PATH . '_cache/avatar/';
        $up_file = TIME_NOW . '_' . $yahoo_id . '.gif';

        $up_path = self::folderUpload($user_id, 'avatar');

        if (self::checkDir($cache_path)) {
            @file_put_contents($cache_path . $up_file, @file_get_contents('http://img.msg.yahoo.com/avatar.php?yids=' . $yahoo_id . '&format=gif'));
            if (file_exists($cache_path . $up_file)) {
                if (self::ftp_image_connect($server_no)) {
                    self::ftp_check_dir($up_path, true, $server_no);

                    if (self::ftp_image_put_file($up_path . $up_file, $cache_path . $up_file, $server_no)) {
                        @unlink($cache_path . $up_file);
                        self::ftp_image_close();
                        return $up_path . $up_file;
                    } else {
                        return 'Could not ftp file: ' . $up_path . $up_file . ', ' . $cache_path . $up_file . ', ' . $server_no;
                    }
                    self::ftp_image_close();
                } else {
                    return 'Could not connect to image server: ' . $server_no;
                }
                @unlink($cache_path . $up_file);
            } else {
                return 'Could not create cache file: ' . $cache_path . $up_file;
            }
        }
        return 'Cache path not exist: ' . $cache_path;
    }

    static function getParamSearch($str_search) {
        $str_search = str_replace(array('+', '/', '|', '-', '*'), "", $str_search);
        $str_search = self::trimSpace($str_search);
        $str_search = str_replace("'", '"', $str_search);
        $str_search = str_replace("&#39;", '"', $str_search);
        $str_search = str_replace("&quot;", '"', $str_search);

        if (eregi('"', $str_search)) {
            $pattern = '#\"(.+?)\"#is';
            preg_match_all($pattern, $str_search, $matches);
            $chars = preg_split($pattern, $str_search);

            $results .= implode(" ", $matches[0]);
            foreach ($chars as $row) {
                if ($row) {
                    $row_array = explode(' ', $row);
                    if (is_array($row_array)) {
                        foreach ($row_array as $word) {
                            if ($word)
                                $results.=" +" . trim($word) . "";
                        }
                    }
                    else {
                        $results.=" +" . trim($row) . "";
                    }
                }
            }
            return $results;
        } else {
            $search_array = explode(' ', $str_search);
            $content = implode(" +", $search_array);
            $content = "+" . $content . '';
            return $content;
        }
    }

    static function trimSpace($str="") {
        if ($str == "") {
            return;
        }
        $str = str_replace("&nbsp;", " ", $str);
        $str = preg_replace('![\t ]*[\r\n]+[\t ]*!', ' ', $str);
        return trim(eregi_replace("[[:space:]]+", " ", trim($str)));
    }

    static function delDoubleSpace($str) {
        if (eregi('  ', $str)) {
            $str = eregi_replace('  ', ' ', $str);
            $str = self::delDoubleSpace($str);
            return $str;
        } else {
            return $str;
        }
    }

    //TuấnNK add ( 2008/05/23 12h17 ) hàm đếm ký tự viết hoa
    static function countUpChars($str) {
        if ($str != '') {
            $strNotAllow = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Á À Ã Ạ Â Ấ Ầ Ẫ Ậ Ă Ắ Ằ Ẵ Ặ É È Ẽ Ẹ Ê Ế Ề Ễ Ệ Í Ì Ĩ Ị Ó Ò Õ Ọ Ô Ố Ồ Ỗ Ộ Ơ Ớ Ờ Ỡ Ợ Ú Ù Ũ Ụ Ư Ứ Ừ Ữ Ự Ý Ỳ Ỹ Ỵ";
            $checkArray = (explode(' ', $strNotAllow));
            $intCount = 0;

            foreach ($checkArray as $checkChar) {
                $intCount+=substr_count($str, $checkChar);
            }
            return ($intCount <= floor(strlen($str) / 3));
        }
        return true;
    }

    static function IsSearchE() {
        $lSearchEngineArray = array("Google", "yahoo", "Fast", "Slurp", "Ink", "Atomz", "Scooter", "Crawler", "MSNbot", "Poodle", "Genius");
        $SearchEngineList = join('|', $lSearchEngineArray);
        if (preg_match("/($SearchEngineList)/is", $_SERVER['HTTP_USER_AGENT'])) {
            return true; // search engine
        }
        return false; // user
    }

    static function isBlackList($user_id_sent, $user_id_receive) {
        //$user_id_sent la user_id cua nguoi gui
        //$user_id_receive la nguoi nhan
        $sql = 'SELECT id FROM black_list WHERE user_id_blacklist = "' . $user_id_sent . '" AND user_id = "' . $user_id_receive . '"';

        if (DB::num_rows(DB::query($sql, __LINE__ . __FILE__))) {
            return true; // da co trong Blacklist
        } else {
            return false;
        }
    }

    static function priceFomart($price, $currency_id=false) {
        if ($price) {
            if ($currency_id) {
                if (isset(CGlobal::$currency[$currency_id])) {
                    $currency_id = " <font color='#B90404'>" . CGlobal::$currency[$currency_id] . "</font>";
                }
                else
                    $currency_id=" <font color='#B90404'>VNĐ</font>";
            }
            else {
                $currency_id = '';
            }
            if (eregi('\.', $price))
                return $price . $currency_id;
            else
                return number_format($price, 0, ',', '.') . $currency_id;
        }
        else {
            return "Liên hệ";
        }
    }

    static function show_error_mes($mess="") {
        //Url::access_denied();
        global $display;

        $display->add('content', $mess);
        $display->output('error', false, 'Error');
    }

    static function mouse_hover($color='#EAF1FB', $return=false) {
        $str = ' onmouseover="tr_color=this.style.backgroundColor;this.style.backgroundColor=\'' . $color . '\'" onmouseout="if(typeof(tr_color)!=\'undefined\'){this.style.backgroundColor=tr_color;}" ';
        if ($return

            )return $str;else
            echo $str;
    }

    static function reload_captcha() {
        $alphanum = "abcdefghiklmopqrstuvwxyz0123456789";
        $new_string = substr(str_shuffle($alphanum), 0, 3);
        $_SESSION["enbac_validate"] = $new_string;
    }

    //get real IP - by TuanNV - 26/09/08
    static function ip_first($ips) {
        if (($pos = strpos($ips, ',')) != false) {
            return substr($ips, 0, $pos);
        } else {
            return $ips;
        }
    }

    static function ip_valid($ips) {
        if (isset($ips)) {
            $ip = self::ip_first($ips);
            $ipnum = ip2long($ip);
            if ($ipnum !== -1 && $ipnum !== false && (long2ip($ipnum) === $ip)) { // PHP 4 and PHP 5
                if (($ipnum < 167772160 || $ipnum > 184549375) && // Not in 10.0.0.0/8
                        ($ipnum < -1408237568 || $ipnum > -1407188993) && // Not in 172.16.0.0/12
                        ($ipnum < -1062731776 || $ipnum > -1062666241))   // Not in 192.168.0.0/16
                    return true;
            }
        }
        return false;
    }

    static function ip() {
        $check = array('HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED',
            'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED',
            'HTTP_VIA', 'HTTP_X_COMING_FROM', 'HTTP_COMING_FROM');

        foreach ($check as $c) {
            //if (self::ip_valid(&$_SERVER[$c])) {
            if (self::ip_valid(@$_SERVER[$c])) {
                return self::ip_first(@$_SERVER[$c]);
            }
        }

        return $_SERVER['REMOTE_ADDR'];
    }

    static function session_started() {
        if (isset($_SESSION)) {
            return true;
        } else {
            return false;
        }
    }

    function limit_char_per_word($str="", $limit=10) {
        if (!AZLib::countUpChars($str)) {
            $str = AZLib::convertUnicodeCaseWithoutHtml($str);
        }

        $arr_tmp = explode(' ', $str);
        $str_tmp = '';
        foreach ($arr_tmp as $ar) {
            if (strlen($ar) > $limit) {
                $str_tmp .= ' ' . substr($ar, 0, $limit);
            } else {
                $str_tmp .= ' ' . $ar;
            }
        }

        return trim($str_tmp);
    }

    //check_badword

    static function get_badword($update_cache = 0, $delcache = false) {
        $badword = array();
        $subDir = 'badword';
        $badword = AZCache::cache('SELECT * FROM bad_words ORDER By exact DESC', __LINE__ . __FILE__, 86400, $update_cache, '', $subDir, $delcache);
        usort($badword, array('AZLib', 'word_length_sort'));
        if ($badword && !$delcache) {
            return $badword;
        }
        return $badword;
    }

    static function word_length_sort($a, $b) {
        if (mb_strlen($a['contents'], 'UTF-8') == mb_strlen($b['contents'], 'UTF-8')) {
            return 0;
        }
        return ( mb_strlen($a['contents'], 'UTF-8') > mb_strlen($b['contents'], 'UTF-8') ) ? -1 : 1;
    }

    static function checkBadWord($str_check='', $return = false, $del_cache = false, $getReason = false) {

        if ($str_check == "" && !$del_cache) {
            return false;
        }

        for ($i = 65; $i <= 90; $i++) {
            $str_check = str_replace("&#" . $i . ";", chr($i), $str_check);
        }

        for ($i = 97; $i <= 122; $i++) {
            $str_check = str_replace("&#" . $i . ";", chr($i), $str_check);
        }

        $str_check = eregi_replace("<br[^>]*>", "\n", $str_check);
        $str_check = eregi_replace("<p[^>]*>", "\n", $str_check);
        $str_check = eregi_replace("</p[^>]*>", "\n", $str_check);

        $str_check = strip_tags($str_check);

        $str_check = str_replace(chr(9), ' ', $str_check);

        $str_check = str_replace("&nbsp;", " ", $str_check);

        $matches = array();
        $arr_badword = AZLib::get_badword();

        if (!$del_cache) {

            foreach ($arr_badword as $badword) {
                $realBad = str_replace('*', '', $badword['contents']);
                $bad = preg_quote($badword['contents']);
                $badword['contents'] = preg_quote($badword['contents']);
                $badword['contents'] = str_replace(array('\*', '\?'), array('(.{0,3})', '(.+)'), $badword['contents']);

                if ($badword['exact']) {
                    if (preg_match('#(^|\s|\b)' . $badword['contents'] . '(\b|\s|!|\?|\.|,|$)#ui', $str_check, $match)) {
                        if ($return) {
                            $bad_arrs[$bad] = $bad;
                            $matches[] = $match[0];
                            $reason_arrs[$realBad] = $badword['reason'];
                        } else {
                            return true;
                        }
                    }
                } else {
                    if (preg_match('#' . $badword['contents'] . '#ui', $str_check, $match)) {
                        if ($return) {
                            $bad_arrs[$bad] = $bad;
                            $matches[] = $match[0];
                            $reason_arrs[$realBad] = $badword['reason'];
                        } else {
                            return true;
                        }
                    }
                }
            }

            if ($return && isset($bad_arrs)) {
                $arrReturn = array(
                    'bad' => implode(', ', $matches),
                    'bad_key' => str_replace(array('\*', '\?'), '', implode(', ', $bad_arrs))
                );
                if ($getReason) {

                    $arrReturn += array(
                        'reason' => $reason_arrs
                    );
                }
                return $arrReturn;
            } else {
                return false;
            }
        }
    }

    static function del_reason_mod($id) {
        if ($id > 0) {

            DB::query("DELETE FROM bad_content WHERE id_item = " . $id . " AND type = 3");
            return true;
        }else
            return false;
    }

    function convertCurrency($price, $currency_id) {
        if ($currency_id == 2) {
            $price = $price * CGlobal::$exchange;
        } 
        return $price;
    }

    function getTopCats()
    {
        self::getCats();

        $allCategories = array();

        if (CGlobal::$subCategories) {
            foreach (array_keys(CGlobal::$subCategories) as $id) {
                if (isset(CGlobal::$allCategories[$id]))
                    $allCategories[$id] = CGlobal::$allCategories[$id]['name'];
            }
        }
        return $allCategories;
    }

    function is_mobile($value) {

        $arr_service = array('091', '090', '093', '094', '098', '099', '096', '092', '097', '095', '016', '012', '019');

        if ($value == "") {
            return false;
        }

        if (substr($value, 0, 1) != "0") {
            return false;
        }

        if (!in_array(substr($value, 0, 3), $arr_service)) {
            return false;
        }
        return true;
    }

    static function check_uri() {
        if (!self::$check_uri) {
            CGlobal::$request_uri = $_SERVER['REQUEST_URI'];
            if (isset($_SERVER['HTTP_REFERER'])) {
                CGlobal::$referer_url = $_SERVER['HTTP_REFERER'];
            }

            CGlobal::$query_string = $_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '';
            $dir = (dirname($_SERVER['SCRIPT_NAME']) ? dirname($_SERVER['SCRIPT_NAME']) : '');

            $dir = str_replace('\\', '/', $dir);

            if ($dir && $dir != '/' && $dir != './') {
                if ($dir[0] != '/') {
                    $dir = '/' . $dir;
                }
                $dir.=$dir[strlen($dir) - 1] != '/' ? '/' : '';
                CGlobal::$query_string = str_replace($dir, '', CGlobal::$request_uri);
            } else {
                $uri = CGlobal::$request_uri;
                if (strlen($uri) > 1) {

                    while ($uri[0] == '/') {
                        $uri = substr($uri, 1, strlen($uri) - 1);
                    }

                    CGlobal::$query_string = $uri;
                    unset($uri);
                } else {
                    CGlobal::$query_string = '';
                }
            }

            self::$check_uri = true;
        }
    }

    function getTotalPerCategory($keywords) {
        require ( "./includes/sphinxapi.class.php" );
        $q = $keywords;

        $mode = SPH_MATCH_EXTENDED;

        $item = array();
        $comma_separated = "";
        //Init config
        $host = SPHINX_SERVER;
        $port = SPHINX_PORT;
        $index = '*';

        $ranker = SPH_RANK_PROXIMITY_BM25;

        $cl = new SphinxClient ();

        $cl->SetServer($host, $port);
        $cl->SetConnectTimeout(1);
        $cl->SetWeights(array(100, 1));
        $cl->SetMatchMode($mode);
        $cl->SetArrayResult(true);
        $cl->SetFilter('status', array('1'));
        $cl->SetGroupBy("level_1_catid", SPH_GROUPBY_ATTR, "@count DESC");

        $res = $cl->Query($q, $index);
        $arr = array();
        if ($res && isset($res["matches"])) {
            if (is_array($res["matches"])) {
                foreach ($res["matches"] as $results) {
                    $arr[] = $results["attrs"];
                }
            }
        }

        return $arr;
    }

    static function get_list_ban_ip() {
        $list_ip = array();
        if (MEMCACHE_ON) {
            $list_ip = AZMemcache::do_get('list_ban_ip');
        }
        if (!$list_ip) {
            $sql = "select * from ban_ip";
            $list_ip_temp = DB::fetch_all_array($sql);
            foreach ($list_ip_temp as $value) {
                $list_ip[$value['ip']] = $value;
            }
        }
        return $list_ip;
    }

    static function getXml($xmlFile = 'http://admicro2.vcmedia.vn/adt/cpc/zones.xml') {
        $xml = new XMLReader();
        $xml->open($xmlFile);
        $assoc = AZLib::xml2assoc($xml);
        $xml->close();
        return (AZLib::optArr($assoc));
    }

    static function xml2assoc(&$xml) {
        $assoc = NULL;
        $n = 0;
        while ($xml->read()) {
            if ($xml->nodeType == XMLReader::END_ELEMENT)
                break;
            if ($xml->nodeType == XMLReader::ELEMENT and !$xml->isEmptyElement) {
                if ($xml->depth == 2) {
                    $assoc[$xml->name] = AZLib::xml2assoc($xml);
                } else {
                    $assoc[$n][$xml->name] = AZLib::xml2assoc($xml);
                }
                $n++;
            } else if ($xml->isEmptyElement) {
                $assoc[$n][$xml->name] = "";
                $n++;
            } else if ($xml->nodeType == XMLReader::TEXT) {
                $assoc = $xml->value;
            }
        }
        return $assoc;
    }

    static function optArr(&$mData) {
        if (is_array($mData)) {
            if (count($mData) == 1) {
                $mData = array_shift($mData);
                if (is_array($mData)) {
                    foreach ($mData as &$aSub) {
                        AZLib::optArr($aSub);
                    }
                }
            } else {
                foreach ($mData as &$aSub) {
                    AZLib::optArr($aSub);
                }
            }
        }
        return $mData;
    }

    static function genUniqueFileName($str = '') {
        $str = explode('.', $str);
        $str = array_pop($str);
        $mini = microtime(true);
        return $mini . '.' . $str;
    }

    //TuanNK 2010.08.06
    static function checkItem() {//check trạng thái và quyền xem của Item: chỉ đc chạy trong trong hàm khởi tạo lớp của từng Module
        if (!Item::$item || (Item::$item && Item::$item['status'] == -1)) {
            //Ko index đối với SEO
            header("HTTP/1.0 404 Not Found");
            CGlobal::$robotContent = "NOINDEX, FOLLOW";
            CGlobal::$gBContent = "noindex,follow";
        }

        if (Item::$item) {
            Item::$item['display'] = 1;

            //Check trạng thái tin và quyền thao tác:
            if (Item::$item['status'] != 1) {//Tin bị kiểm duyệt
                if (!User::have_permit(ADMIN_ITEM))
                {
                    Item::$item['display'] = 0;
                }
            }
        }
    }

    static function sortByLength($a, $b) {
        return strlen($b) - strlen($a);
    }

    static function HighLightKeyword($string, $keywords, $limit=0, $style="font-weight:bold;", $emphasis='...') {
        $arrKeywords = explode(',', $keywords);
        $highlighted = '';
        usort($arrKeywords, "AZLib::sortByLength"); // Sắp xếp giảm dần theo số ký tự, đảm bảo không highlight 1 keyword ít ký tự nhiều lần

        if ($limit) {
            $arrWords = explode(' ', $string);

            $wordCount = count($arrWords);

            if ($wordCount > $limit) { // Cắt xâu có bao gồm keyword, nếu có $limit
                $start = 0;
                $len = $limit;

                for ($i = 0; $i < $wordCount; $i++) {
                    if (stripos($arrWords[$i], $arrKeywords[0]) !== false) {
                        if (($i - 5) > 0)
                            $start = $i - 5; // lấy 5 word trước khi keyword xuất hiện
 if (($wordCount - $start) < $limit) { // Số lượng word lấy ra ít hơn $limit truyền vào
                            //Dịch offset start lùi về trước, tính từ cuối xâu
                            $start = $wordCount - $limit;
                        }
                        break;
                    }
                }
                if ($len)
                    $string = ($start ? $emphasis : '') . implode(' ', array_slice($arrWords, $start, $len)) . (($start + $limit < $wordCount) ? $emphasis : '');
            }
        }

        foreach ($arrKeywords as $keyword) {
            if (!$highlighted || ($highlighted && (stripos($highlighted, $keyword) === false))) { // Keyword chưa được highlight
                //$string = preg_replace("/\b($keyword)\b/i", '<span style="' . $style . '">\1</span>', $string);
                $string = str_ireplace($keyword, '<span style="' . $style . '">' . $keyword . '</span>', $string);
                $highlighted .= ( $highlighted ? ',' : '') . $highlighted;
            }
        }
        return $string;
    }
    
    static function getPrice( $price,$currency_id=1)
	{
		if(!$price)
		return "Liên hệ";
		
		$price=number_format($price,2,',','.');
		$price= str_replace(',00', '', $price);
		
		if($currency_id==1)
		{
			return $price.' VNĐ';
		}
		else
		{
			return $price.' USD';
			//return "<span>$</span>".$price;
			
			/*$icon = "$";
			return $icon . $price;*/
			
			//return $price."$";
		}
	}
	
	static function money($money = 0)
	{
		if($money < 1000)
		{
			return 0;
		}
		if($money >= 1000000000)
		{
			return "trên 1 tỷ";
		}
		
		if($money >= 1000000)
		{
			return str_replace(',0','',number_format(($money/1000000),1,",","."))." triệu";
		}
		
		if($money >= 1000)
		{
			return number_format(($money/1000),0,",",".")." ngàn";
		}
	}
	
	static function uploadDocPath($subdir = 'document'){
		$dir = DATA_PATH."$subdir/".date('Y').".".date('m')."/";
		
		self::CheckDir($dir);
		return	$dir;
	}
	
	static function excel_col2num($col_name)
	{
		$col_name = strtoupper($col_name);
		
		$col_num = 0;
		
		for($i = 0; $i < strlen($col_name); $i++)
		{
			$col_num += $col_name{$i} == '0' ? 0 : (ord($col_name{$i}) - 64) * pow(26, strlen($col_name) - $i -1);
		}
	   
	    return $col_num;
	}
	
	static function excel_num2col($col_num)
	{
		return ($col_num <= 26) ? chr((int)$col_num + 64) : self::excel_num2col($col_num / 26) . self::excel_num2col($col_num % 26);
		/*
		if ($col_num <= 26){
			return chr((int)$col_num + 64);
		}
		$col_num--;
		return self::excel_num2col($col_num / 26) . self::excel_num2col(($col_num % 26) + 1);*/
	}
	
	static function delDir($dirDelete)
	{
		if(is_dir($dirDelete))
		{
			$list_contents=scandir($dirDelete);
			
			if($list_contents)
			{
				foreach ($list_contents as $file)
				{
					if($file!='.' && $file!='..')
					{
						if(is_dir($dirDelete.$file))
						{
							self::delDir($dirDelete.$file.'/');
						}
						else 
							@unlink($dirDelete.$file);
					}
				}
			}
			
			@rmdir($dirDelete);
		}
	}
	
	static function getRank($product,$rate_act=false,$type=0)
	{
		$tooltip='<div style="padding:4px;background-color:#FFFFFF;border:1px solid #CCCCCC;">';
		if(!$type)
		{
			if($product['f_rank'])
				$tooltip.="<b>Tính năng:</b> ".number_format($product['f_rank'],1,'.',',')."/10 - ".$product['f_rate_num']." lượt đánh giá</br>";
			else 
				$tooltip.="<b>Tính năng:</b> Chưa có đánh giá.</br>";
			if($product['d_rank'])
				$tooltip.="<b>Kiểu dáng:</b> ".number_format($product['d_rank'],1,'.',',')."/10 - ".$product['d_rate_num']." lượt đánh giá</br>";
			else 
				$tooltip.="<b>Kiểu dáng:</b> Chưa có đánh giá.</br>";
			if($product['u_rank'])
				$tooltip.="<b>Tiện dụng:</b> ".number_format($product['u_rank'],1,'.',',')."/10 - ".$product['u_rate_num']." lượt đánh giá</br>";
			else 
				$tooltip.="<b>Tiện dụng:</b> Chưa có đánh giá.</br>";
				
			$tooltip.="</div>";
			if($rate_act)
				return "<img onclick='show_tab(3); window.scroll(0,jQuery(\"#header_tab_3\").offset().top);' style='cursor:pointer;' src='images/star".(int)$product['rank'].".png' ".self::tooltipContent($tooltip)."/>";
			else 
				return "<img src='images/star".round($product['rank']).".png' ".self::tooltipContent($tooltip)."/>";
			
		}
		else 
		{
			if($type==1)
			{
				$type='f_rank';
				
				if($product['f_rank'])
				{
					$tooltip.="<b>Tính năng: ".number_format($product['f_rank'],1,'.',',')."/10 - ".$product['f_rate_num']." lượt đánh giá</b></br>";
					$text="<b>Tính năng:".number_format($product['f_rank'],1,'.',',')."/10 - ".$product['f_rate_num']." lượt đánh giá</b></br>";	
				}
				else 
				{
					$tooltip.="Chưa có đánh giá.</br>";
					$text="<b>Tính năng:0/10 - ".$product['u_rate_num']." lượt đánh giá</b></br>";	
				}
			}
			elseif ($type==2)
			{
				$type='d_rank';
				if($product['d_rank'])
				{
					$tooltip.="<b>Kiểu dáng:</b> ".number_format($product['d_rank'],1,'.',',')."/10 - ".$product['d_rate_num']." lượt đánh giá</br>";
					$text="<b>Kiểu dáng:".number_format($product['d_rank'],1,'.',',')."/10 - ".$product['d_rate_num']." lượt đánh giá</b></br>";
				}
				else 
				{
					$tooltip.="Chưa có đánh giá.</br>";
					$text="<b>Kiểu dáng:0/10 - ".$product['u_rate_num']." lượt đánh giá</b></br>";	
				}
			}
			elseif ($type==3)
			{
				$type='u_rank';
				if($product['u_rank'])
				{
					$tooltip.=number_format($product['u_rank'],1,'.',',')."/10 - ".$product['u_rate_num']." lượt đánh giá</br>";
					$text="<b>Tiện dụng:".number_format($product['u_rank'],1,'.',',')."/10 - ".$product['u_rate_num']." lượt đánh giá</b></br>";
				}
				else 
				{
					$tooltip.="Chưa có đánh giá.</br>";
					$text="<b>Tiện dụng:0/10 - ".$product['u_rate_num']." lượt đánh giá</b></br>";	
				}
			}
			
			$tooltip.="</div>";
			return $text."<img src='images/star".round($product[$type]).".png' ".AznetLib::tooltipContent($tooltip)."/><br />";
		
		}
		
	}
	
	//Hàm hiển thị tooltip của sản phẩm
	static function tooltipContent($content)
	{
		$onmouseover='';
		
		if($content!=''){
			$content=str_replace(array(chr(10),chr(13),"\n"),'',$content);
			$content=str_replace(array('\"','"'),array('\'',"'"),$content);
		
			$onmouseover=' onmouseover="showtip(\''.addslashes($content).'\'); " onmouseout="hidetip();" ';
		}
		
		return $onmouseover;
	}
}
//register_shutdown_function(array("AZLib","ftp_image_close"));
?>